package com.edu.schoolforum.controller;

import com.edu.schoolforum.dto.WebLoginDto;
import com.edu.schoolforum.dto.WebSignDto;
import com.edu.schoolforum.enums.ResultEnum;
import com.edu.schoolforum.pojo.User;
import com.edu.schoolforum.service.UserService;
import com.edu.schoolforum.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author tao
 * @date 2021/8/4 18:41
 */
@Controller
@RestController
@RequestMapping("/api")
public class LoginController {
    @Autowired
    UserService userService;

    @ResponseBody
    @PostMapping("/login/web")
    public CommonResult login(@RequestBody WebLoginDto webLoginDto){
        User u=new User();
        u.setName(webLoginDto.getName());
        u.setPassword(webLoginDto.getPassword());
        User user= userService.login(u);
        Integer status=userService.getUserStatus(user);
       if(user!=null&&status.equals(1)){
           return CommonResult.success(user);
       }else{
           return CommonResult.fail(ResultEnum.LOGIN_EXCEPTION);
       }

    }

    @ResponseBody
    @PostMapping("/register")
    public CommonResult sign(@RequestBody WebSignDto webSignDto){
        User user=userService.getUserByName(webSignDto.getName());
        if(user!=null){
            return CommonResult.fail(ResultEnum.ACCOUNT_HAS_EXIT);
        }
        User newUser=new User();
        if(webSignDto.getName()!=null){
            newUser.setName(webSignDto.getName());
        }
        if(webSignDto.getPassword()!=null){
            newUser.setPassword(webSignDto.getPassword());
        }
        if(webSignDto.getTelephone()!=null){
            newUser.setTelephone(webSignDto.getTelephone());
        }
        newUser.setAvatarUrl("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png");
        newUser.setAuthority(0);  //注册一般为普通用户
        newUser.setStatus(1);     //状态一般为可用
        int i=userService.insertUser(newUser);
        if(i==0){
            return CommonResult.fail(ResultEnum.INSERT_USER_FAIL);
        }
        return CommonResult.success();
    }

    @GetMapping("/hello")
    public List<User> getUser(){
        List<User> list=userService.getList();
        for (User a:list){
            System.out.println(a);
        }
        return list;
    }
}
